"use strict";

module.exports = (app) => {
  const { STRING, INTEGER, Op } = app.Sequelize;

  const Word = app.model.define(
    "english_word",
    {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      word: STRING(255),
      sent: STRING(255),
      chinese: STRING(255),
    },
    {
      freezeTableName: true,
      timestamps: false, // 禁用自动时间戳
    }
  );

  Word.associate = function() {
    Word.belongsToMany(app.model.User, {
      as: 'user',
      through: app.model.Progress,
      foreignKey: 'word_id', // 用户ID外键
      otherKey: 'user_id', // 单词ID外键
    });
    Word.hasMany(app.model.WordFavorites, {
      foreignKey: 'word_id',
      as: 'favorited_by',
    });
  };

  // Word.queryWordList = async function(currentPageSize, currentPage, class_name = '') {
  //   return await this.findAndCountAll({
  //     where: {
  //       word: {
  //         [Op.substring]: class_name,
  //       },
  //     },
  //     offset: currentPageSize * (currentPage - 1),
  //     limit: currentPageSize,
  //   });
  // };

  Word.queryWordsByIds = async function (ids) {
    return await this.findAll({
      where: {
        id: {
          [Op.in]: ids,
        },
      },
      attributes: ["word"],
      raw: true,
    });
  };

  return Word;
};
